package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Board;
import com.conversationboard.model.Boards;
import com.conversationboard.model.Colour;
import com.conversationboard.model.User;
import com.conversationboard.model.preferences.SiteNewPostsViewInfo;

@WebServlet(name = "UpdateSiteNewPostsPreferencesControllerServlet", urlPatterns = "/UpdateSiteNewPostsPreferencesControllerServlet")
public class UpdateSiteNewPostsPreferencesControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 3522898977770477847L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			/* If you're restoring the defaults */

			if (request.getParameter("restoreDefaults") != null) {
				user.getPreferences().restoreDefaultSiteNewPostsView();

				request.setAttribute("message", "Defaults settings have been restored.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);

				return;
			}

			List<Board> boards = Boards.getAuthorisedBoards(user, false);

			Map<Integer, SiteNewPostsViewInfo> preferences = new HashMap<Integer, SiteNewPostsViewInfo>();

			for (Board board : boards) {

				String hide = request.getParameter("hide" + board.getBoardId());
				String colour = request.getParameter("colour" + board.getBoardId());

				SiteNewPostsViewInfo viewInfo = new SiteNewPostsViewInfo();
				viewInfo.setShow(hide == null);

				if (colour != null) {
					viewInfo.setColour(colour);
					viewInfo.setDarkerColour(Colour.getDarkerVersion(colour));
				} else {
					viewInfo.setColour("#000");
				}

				preferences.put(board.getBoardId(), viewInfo);
			}

			user.getPreferences().setSiteNewPostsViewInfo(preferences);
			user.getPreferences().store();

			RequestDispatcher dispatcher = request.getRequestDispatcher("/CustomiseSiteNewPostsControllerServlet");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}
}
